<?php

namespace app\admin\controller;

use app\api\model\Privatechat;
use think\Db;
use think\Session;
use app\api\model\Task;

class Cluster extends Common
{
    public function index()
    {
        $where = [];

        $admin = Session::get('admin', 'mmjtAdmin');
        $type = db('admin_type')->where('id', $admin['type'])->value('title');
        if ($type == '城市代理') {
            if (substr($admin['city'], -1) == '市') {
                $admin['city'] = substr($admin['city'], 0, mb_strlen($admin['city']) - 1);
            }
            $where['city'] = ['like', $admin['city'] . '%'];
        }

        $types = input('types/d');
        if ($types) {
            $where['types'] = $types;
        }

        $status = input('status');

        if ($status !== null) {
            $where['status'] = $status;
        }

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            if (in_array($search_type, ['id', 'yqr'])) {
                $where[$search_type] = $search_name;
            } else {
                $where[$search_type] = ['like', '%' . $search_name . '%'];
            }
        }

        $data = Db::name('cluster')->where($where)->order('id desc')->paginate(_getCachePages(), false, ['query' => request()->param()])->each(function ($item, $key) {
            $user = Db::name('user')->find($item['user_id']);
            $item['user_name'] = $user ? $user['name'] : '';

            return $item;
        });

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);

        $this->assign('types', $types);
        $this->assign('status', $status);

        return $this->fetch();
    }

    public function add()
    {
        $id = input('id');

        if (request()->isAjax()) {

            $post = input('post.');

            if (!isset($post['longitude']) || !$post['longitude']) {
                unset($post['longitude']);
            }

            if (!isset($post['latitude']) || !$post['latitude']) {
                unset($post['latitude']);
            }

            if (!$id) {
                if (!isset($post['name']) || !$post['name']) {
                    return ['err' => '名称不能为空'];
                }

                $db = Db::name('cluster')->insert($post);

                if ($db) {
                    $data = ['ret' => '添加成功'];
                } else {
                    $data = ['err' => '添加失败'];
                }
            } else {
                if (!isset($post['name']) || !$post['name']) {
                    return ['err' => '名称不能为空'];
                }

                $db = Db::name('cluster')->where('id', $id)->update($post);
                if ($db !== false) {
                    $data = ['ret' => '修改成功'];
                } else {
                    $data = ['err' => '修改失败'];
                }
            }
        } else {
            if ($id) {
                $name = Db::name('cluster')->find($id);

                if ($name) {
                    $this->assign('name', $name);
                } else {
                    return ['err' => 'id参数错误'];
                }
            }

            $data = $this->fetch();
        }
        return $data;
    }

    public function location()
    {
        $action = input('action');
        $id = input('id/d');

        $this->assign('action', $action);
        $this->assign('id', $id);
        return $this->fetch();
    }

    public function check()
    {
        $where = [];

        $status = input('status');
        if ($status !== null) {
            $where['t1.status'] = $status;
        }

        $search_name = input('param.name');
        $search_type = input('param.search');
        if ($search_name && $search_type) {
            $where['t1.' . $search_type] = ['like', '%' . $search_name . '%'];
        }

        $data = Db::name('cluster_user t1')
            ->field('t1.*,t2.name, t3.name username, t3.phone')
            ->join('cluster t2', 't2.id = t1.cluster_id')
            ->join('user t3', 't3.id = t1.user_id')
            ->where($where)
            ->order('t1.id desc')
            ->paginate(_getCachePages(), false, ['query' => request()->param()]);

        $this->assign('data', $data);
        $page = $data->render();
        $this->assign('page', $page);

        $this->assign('status', $status);

        return $this->fetch();
    }

    public function hide()
    {
        if (request()->isAjax()) {

            $id = input('id');
            $status = input('status');

            $text = ['1' => '<font color="#1ab394">通过</font>', '-1' => '<font color="#f00">拒绝</font>'];

            $cluster_user = Db::name('cluster_user')->find($id);

            if ($cluster_user) {
                $cluster = Db::name('cluster')->find($cluster_user['cluster_id']);

                if (!$cluster) {
                    return ['家族不存在'];
                }

                $chat_ids = json_decode($cluster_user['data'], true)['chat_id'];
                $chat_ids = explode(',', $chat_ids);

                if ($status == 1) {
                    Db::name('cluster')->where(['id' => $cluster_user['cluster_id']])->setInc('count');

                    $content = '你申请加入家族 [' . $cluster['name'] . '] 已通过';

                    // 任务
                    Task::finish('join_family', $cluster_user['user_id']);
                } else {
                    $content = '很遗憾，你申请加入家族 [' . $cluster['name'] . '] 未通过';
                }

                Privatechat::notice($cluster_user['user_id'], $content);
    
                if ($chat_ids) {
                    Privatechat::update(['id' => ['in', $chat_ids], 'state' => 1]);
                }

                $db = Db::name('cluster_user')->where(['id' => $id])->update(['status' => $status, 'update_time' => time()]);

                if ($db) {
                    $data = [$text[$status]];
                } else {
                    $data = ['删除失败'];
                }
            } else {
                $data = ['申请不存在'];
            }
        } else {
            $data = ['提交错误'];
        }
        return $data;
    }

    public function del()
    {
        if (request()->isAjax()) {

            $id = input('id');
            if ($id) {
                $db = Db::name('cluster')->delete($id);
                if ($db) {
                    $data = ['ret' => '删除成功'];
                } else {
                    $data = ['err' => '删除失败'];
                }
            } else {
                $data = ['err' => 'id参数错误'];
            }
        } else {
            $data = ['err' => '提交参数错误'];
        }
        return $data;
    }
}
